import { useMutation } from "react-relay";
import { useCallback } from "react";
import {
  useCloseIssueMutationResponse,
  CloseIssueInput
} from "./__generated__/useCloseIssueMutation.graphql";

const graphql = require("babel-plugin-relay/macro");


const mutation = graphql`
  mutation useCloseIssueMutation($input: CloseIssueInput!) {
    closeIssue(input: $input) {
      issue {
        closed
      }
    }
  }
`;


function getOptimisticResponse(
  issueId: string
): useCloseIssueMutationResponse {
  /**
   * 太乐观了， 后端都还没通知啊，就修改。
   * */
  return {
    closeIssue: {
      issue: {
        closed: false
      }
    }
  };
}

export default function useCloseIssueMutation() {
  const [commit] = useMutation(mutation);
  return [
    useCallback(
      (issueId: string) => {
        const input: CloseIssueInput = {
          issueId
        };

        return commit({
          variables: { input },
          optimisticResponse: getOptimisticResponse(issueId)
        });
      },
      [commit]
    )
  ];
}
